﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.ProcessManager.Entity;
using System.Threading;

namespace PSE.ProcessManager.ResourceAccess.FileSystemProvider
{
    public class InteligenceModuleResourceAccess : BaseFileAccess
    {
        private static Mutex _mtxLock = new Mutex(false, "PSE.ProcessManager.ResourceAccess.FileSystemProvider.InteligenceModule.MtxLock");

        private string _filePath;
        public InteligenceModuleResourceAccess(string filePath)
        {
            _filePath = filePath;
        }

        public List<InteligenceModuleEntity> GetAll()
        {
            List<InteligenceModuleEntity> ret = base.LoadFromXmlFile<List<InteligenceModuleEntity>>(_filePath);
            if (ret == null)
                ret = new List<InteligenceModuleEntity>();

            return ret;
        }

        public InteligenceModuleEntity GetOne(int id)
        {
            List<InteligenceModuleEntity> result = GetAll();
            if (result.Count > 0)
            {
                return result.Find(im => im.Id == id);
            }
            else
                return null;
        }

        private int CompareById(InteligenceModuleEntity a, InteligenceModuleEntity b)
        {
            return a.Id.GetValueOrDefault().CompareTo(b.Id.GetValueOrDefault());
        }

        public void SaveToFile(List<InteligenceModuleEntity> listInteligenceModule)
        {
            try
            {
                _mtxLock.WaitOne();


                if (listInteligenceModule != null)
                    listInteligenceModule.Sort(new Comparison<InteligenceModuleEntity>(CompareById));

                //salvar
                base.SaveToXmlFile(_filePath, listInteligenceModule);
            }
            catch
            {
                throw;
            }
            finally
            {
                _mtxLock.ReleaseMutex();
            }
        }
    }
}
